package dao

import (
	"context"
	"go-mall/model"
	"gorm.io/gorm"
)

type CartDao struct {
	*gorm.DB
}

func NewCartDao(ctx context.Context) *CartDao {
	return &CartDao{NewDBCliet(ctx)}
}

func (dao *CartDao) CreateCart(cart *model.Cart) error {
	return dao.DB.Model(&model.Cart{}).Create(cart).Error
}

func (dao *CartDao) ListCartByUserId(uid uint) (Cart []*model.Cart, err error) {
	err = dao.DB.Model(&model.Cart{}).Where("user_id = ?", uid).Find(&Cart).Error
	return
}

func (dao *CartDao) FindByIdAndUidAndPid(pId, uId uint) (cart *model.Cart, err error) {
	err = dao.DB.Model(&model.Cart{}).Where("product_id=? AND user_id=?", pId, uId).Find(&cart).Error
	return
}

func (dao *CartDao) UpdateNumById(cId uint, num int) error {
	return dao.DB.Model(&model.Cart{}).Where("id=?", cId).Update("num", num).Error
}

func (dao *CartDao) DeleteCartByCartId(cId, uId uint) error {
	return dao.DB.Model(&model.Cart{}).Where("id=? AND user_id=?", cId, uId).Delete(&model.Cart{}).Error
}

func (dao *CartDao) DeleteCartListByCartId(carts []model.Cart, uId uint) error {
	return dao.DB.Model(&model.Cart{}).Delete(&carts).Error
}
